#!/bin/bash
# Copyright 2017 Mirantis
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Some parts are based on https://github.com/docker/docker/blob/master/hack/dind
# Copyright 2012-2016 Docker, Inc.
# Original version by Jerome Petazzoni <jerome@docker.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -o errexit
set -o nounset
set -o pipefail
set -o errtrace

DIND_STORAGE_DRIVER="${DIND_STORAGE_DRIVER:-overlay2}"

# Ensure shared mount propagation to ensure volume mounting works for Kubernetes.
# Took it from here:
# https://github.com/marun/dkr-systemd-dind/blob/25702cf7a4a73bcc355a492f4e5ca96cc562a5a5/dind-setup.sh#L46
mount --make-shared /

# securityfs is mounted by systemd itself if it isn't being run in a container.
# In case of containerized systemd, it doesn't want to have systemd mounted
# on startup because it wants to avoid dealing with IMA in this case.
# See https://github.com/systemd/systemd/blob/master/src/shared/ima-util.c
# IMA stands for Integrity Measurement Architecture
# https://sourceforge.net/p/linux-ima/wiki/Home/#integrity-measurement-architecture-ima
# Still, we need to have securityfs in DIND for AppArmor detection and
# support for --privileged mode, so we're mounting it there.
if [ -d /sys/kernel/security ] && ! mountpoint -q /sys/kernel/security; then
  mount -t securityfs none /sys/kernel/security || {
    echo >&2 'Could not mount /sys/kernel/security.'
    echo >&2 'AppArmor detection and --privileged mode might break.'
  }
fi

# Mount /tmp (conditionally)
if ! mountpoint -q /tmp; then
  mount -t tmpfs none /tmp
fi

echo "Trying to load overlay module (this may fail)" >&2
modprobe overlay || true

extra_opts=()
if [[ ${DIND_STORAGE_DRIVER} == overlay2 ]] && grep -q '[[:blank:]]overlay[[:blank:]]*' /proc/filesystems; then
  # --storage-opt overlay2.override_kernel_check=true is needed for CentOS systems
  extra_opts+=(--storage-driver="${DIND_STORAGE_DRIVER}"
               --storage-opt overlay2.override_kernel_check=true)
else
  extra_opts+=(--storage-driver="${DIND_STORAGE_DRIVER}")
fi

# FIXME: this fix really concerns kubelet, so perhaps it should go
# into another place
# Kubelet will try to contact GCE metadata server on startup if
# it detects a GCE VM and this breaks kdc on Travis
if [[ $(cat /sys/class/dmi/id/product_name) =~ Google ]]; then
  echo "KDC" >/dmi_product_name
  mount --bind /dmi_product_name /sys/class/dmi/id/product_name
fi

# Directories bind-mounted from /dind are not managed by the Docker's snapshotting mechanism, e.g. overlayfs.
# Some apps expect /var/lib/kubelet/pods/{podid}/volumes/kubernetes.io~empty-dir to be non-overlayfs.
mkdir -p /dind/pods /var/lib/kubelet/pods
grep "/var/lib/kubelet/pods[[:space:]]" /proc/mounts  || mount --bind /dind/pods /var/lib/kubelet/pods

# `kubectl logs -f` expects /var/log/pods to be non-overlayfs.
mkdir -p /dind/logs /var/log/pods
grep "/var/log/pods[[:space:]]" /proc/mounts || mount --bind /dind/logs /var/log/pods

if [[ ${DIND_CRI} = containerd ]]; then
  extra_opts+=("--cri-containerd")
fi

exec /usr/bin/dockerd -H unix:// "${extra_opts[@]}" --data-root /dind/docker "$@"
